package com.cloudy.core.thrift.client;

import com.cloudy.core.thrift.zookeeper.client.IAddressProvider;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.TServiceClientFactory;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.net.InetSocketAddress;

/**
 * Created by vipshop on 16/11/18.
 */
public class ThriftClientBootstrap {
    private final IAddressProvider addressProvider;
    private final TServiceClientFactory<TServiceClient> clientFactory;

    ThriftClientBootstrap(IAddressProvider addressProvider,
                                      TServiceClientFactory<TServiceClient> clientFactory) throws Exception {
        this.addressProvider = addressProvider;
        this.clientFactory = clientFactory;
    }

    TServiceClient create() throws TTransportException {
        InetSocketAddress address = addressProvider.selector();
        TSocket tsocket = new TSocket(address.getHostName(), address.getPort());
        TTransport transport = new TFramedTransport(tsocket);
        TProtocol protocol = new TBinaryProtocol(transport);
        TMultiplexedProtocol multiProtocol = new TMultiplexedProtocol(protocol,"HelloService");
        TServiceClient client = this.clientFactory.getClient(multiProtocol);
        transport.open();
        return client;
    }
}
